package org.cardoso.web.jsf;

import java.io.Serializable;
import java.util.List;

import javax.faces.event.ActionEvent;

import org.cardoso.persistence.EntityBean;
import org.cardoso.persistence.Persistence;
import org.cardoso.persistence.filter.FindByExample;

public abstract class ManagedBeanBasic<T extends EntityBean> extends ManagedBeanSpring implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private Class<T> entityClass;
	private EntityBean entity;
	private List<EntityBean> entityList;

	protected abstract Persistence<T> getPersistence();
	
	public ManagedBeanBasic() {
		super();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ManagedBeanBasic(Class entityClass) {
		super();
		this.entityClass = entityClass;
	}
	
	@Override
	public void initComponents() {
		initializeEntity();
	}
	
	public void newEntity() {
		initializeEntity();
	}
	
	private void initializeEntity() {
		try {
			this.entity = this.entityClass.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void save(ActionEvent event) {
		saveEntity(event);	
	}
	
	public void saveRefreshGrid(ActionEvent event) {
		saveEntity(event);
		refreshGrid();
	}
	
	@SuppressWarnings("unchecked")
	private void saveEntity(ActionEvent event) {
		try {
			getPersistence().save((T)entity);
			setOncompleteSave(ONCOMPLETE_SAVE_SUCESS);
		} catch (Exception e) {
			setOncompleteSave(ONCOMPLETE_SAVE_FAIL);
			e.printStackTrace();
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public void remove(ActionEvent event) {
		try {
			getPersistence().remove((T) entity);
			newEntity();
			refreshGrid();
			setOncompleteRemove(ONCOMPLETE_REMOVE_SUCESS);
			throw new Exception();
		} catch (Exception e) {
			setOncompleteRemove(ONCOMPLETE_REMOVE_FAIL);
			e.printStackTrace();
		}
	}
	
	public void entitySelected() {
		System.out.println("---------> EntitySelected: [id = " + getEntity().getId() + "]");
	}
	
	@Override
	public void refreshGrid() {
		this.paginator.update();
	}
	
	@Override
	public Long count() {
		return getPersistence().count(FindByExample.create(getEntity()));
	}

	@SuppressWarnings("unchecked")
	@Override
	public void find(Integer firstResult, Integer maxResult) {
		this.entityList = (List<EntityBean>) getPersistence().find(FindByExample.create(getEntity()).setFirstResult(firstResult).setMaxResults(maxResult));
	}

	public EntityBean getEntity() {
		return entity;
	}

	public void setEntity(EntityBean entity) {
		this.entity = entity;
	}

	public List<EntityBean> getEntityList() {
		return entityList;
	}

	public void setEntityList(List<EntityBean> entityList) {
		this.entityList = entityList;
	}

}